<?php
namespace App\Models\Traits;
use App\Http\Resources\GoodsResource;
use App\Http\Resources\GoodsSingleResource;
use Illuminate\Support\Carbon;
use Arr;
use Cache;
use App\Models\GoodsWatchLogs;
use App\Models\Goods;
use DB;
trait UserFavouriteGoodsCalculateHelper{

    //存放临时产品
    protected $goods = [];
    //配置信息
    protected $pass_days = 3; //多少天内查看的产品
    protected $goods_number = 6; //取出多少产品

    //缓存相关信息
    protected $cache_base_key = "cpg_favourite_users";
    protected $cache_expire_in_seconds = 60*60*6;

    public function favourite_goods(){

        return Cache::remember($this->cache_base_key.$this->id,$this->cache_expire_in_seconds,function (){
            return $this->calculateFavouriteGoods();
        });
    }

    public function calculateFavouriteGoods(){
            $this->calcuteGoodsWeight();//查看此人三天内产品的权重
            if (count($this->goods)<=0){
               $goods =  Goods::orderBy("order_number","desc")->limit($this->goods_number)->get();
                return GoodsResource::collection($goods);
            }
            $goods = Arr::sort($this->goods,function ($goods){
               return $goods['weight'];
            });
        // 我们需要的是倒序，高分靠前，第二个参数为保持数组的 KEY 不变
        $goods = array_reverse($goods, true);
        // 只获取我们想要的数量
        $goods = array_slice($goods, 0, $this->goods_number, true);
        $favourite_goods = collect();
        foreach ($goods as $k=>$v){
            $goods_info = Goods::findOrFail($v['goods_id']);
            $favourite_goods->push(new GoodsSingleResource($goods_info));
        }
        return $favourite_goods;
    }

    public function calcuteGoodsWeight(){
        $goods  = GoodsWatchLogs::query()
                    ->select(Db::raw('goods_id,count(*) as weight'))
                    ->where('created_at','>=',Carbon::now()->subDays(
                        $this->pass_days
                    ))
                    ->where("user_id","=",$this->id)
                    ->groupBy('goods_id')
                    ->get();
        $this->goods = $goods->toArray();
    }

}
